import 'dart:developer';
import 'dart:io';
import 'dart:typed_data';
import 'package:huxiaodui/api/mobile_app_api.dart';
import 'package:huxiaodui/api/other_api.dart';
import 'package:huxiaodui/api/unit_api.dart';
import 'package:huxiaodui/api/push_api.dart';
import 'package:huxiaodui/api/model/result.dart';
import 'package:huxiaodui/config.dart';
import 'package:huxiaodui/store/store.dart';
import 'package:huxiaodui/utils/aliyun_push.dart';
import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:uuid/v4.dart';

class MobileAppUrl {
  static String unbindEmail = "/mobileApp/unbind/email";

  static String forgetByEmailCode = "/mobileApp/forget/byEmail/code";
  static String forgetByEmail = "/mobileApp/forget/byEmail";

  static String units = "/mobileApp/units";
  static String sameUnits = "/mobileApp/units/same";
  static String alarms = "/mobileApp/alarms";
}

class UnitUrl {
  static String all = "/unit/all";

  static String search = "/unit/search";
  static String id = "/unit/id";
  static String code = "/unit/code";
  static String join = "/unit/join";
  static String quit = "/unit/quit";
}
class AlarmUrl {
  static String add = "/alarm/add";
  static String addMessage = "/alarm/message/add";
  static String delMessage = "/alarm/message/del";
  static String allMessage = "/alarm/message/all";
}

class NoticeUrl{
  static String all = "/notice/all";
}

class OtherUrl {
  static String upload = "/other/upload";
}

class Api {
  static MobileAppApi mobileApp = MobileAppApi();
  static UnitApi unit = UnitApi();
  static PushApi push = PushApi();
  static OtherApi other = OtherApi();

  static Future<Result> request({
    required String url,
    bool fileUpload = false,
    Map<String, dynamic>? data,
    bool isToast = false,
    Function(Result)? success,
    Function(Result)? failure,
    Function? error,
  }) async {
    Dio dio = Dio();

    await Store.reload();
    dio.options.headers['authorization'] = await Store.auth.get() ?? "0";
    dio.options.headers['deviceId'] = SystemPush.deviceId;
    dio.options.headers['deviceType'] = Platform.isAndroid ? "android" : Platform.isIOS ? "ios" : "";
    if(fileUpload) dio.options.contentType = "multipart/form-data; boundary=--${UuidV4().generate()}";

    log("url:$url \n请求头：${dio.options.headers} \n请求内容：$data");

    if (isToast) {
      EasyLoading.show(maskType: EasyLoadingMaskType.black);
    }
    Response response;
    try {
      response = fileUpload ? await dio.post(ApiConfig.httpHost + url, data: FormData.fromMap(data??{})) : await dio.post(ApiConfig.httpHost + url, data: data);

    } catch (e) {
      if (isToast) {
        EasyLoading.dismiss();
      }
      EasyLoading.showError("网络异常");

      if (error != null) error();
      print("请求异常：$e");
      rethrow;
    }
    Result res = Result.fromJson(response.data);

    if (res.success) {
      if (isToast) {
        EasyLoading.dismiss();
        EasyLoading.showSuccess(res.msg);
      }
      if(success != null) success(res);
      return res;
    }else{
      if (isToast) {
        EasyLoading.dismiss();
        EasyLoading.showError(res.msg);
      }
      if(failure != null) failure(res);
      throw Exception(res.msg);
    }

  }


  static Future<Result> bgRequest({
    required String url,
    bool fileUpload = false,
    Map<String, dynamic>? data,
    Function(Result)? success,
    Function(Result)? failure,
    Function? error,
  }) async {
    Dio dio = Dio();
    await Store.reload();
    dio.options.headers['authorization'] = await Store.auth.get() ?? "0";
    dio.options.headers['deviceId'] = SystemPush.deviceId;
    dio.options.headers['deviceType'] = Platform.isAndroid ? "android" : Platform.isIOS ? "ios" : "";
    if(fileUpload) dio.options.contentType = "multipart/form-data; boundary=--${UuidV4().generate()}";
    log("url:$url \n请求头：${dio.options.headers} \n请求内容：$data");
    Response response;
    try {
      response = fileUpload ? await dio.post(ApiConfig.httpHost + url, data: FormData.fromMap(data??{})) : await dio.post(ApiConfig.httpHost + url, data: data);
    } catch (e) {
      if (error != null) error();
      print("请求异常：$e");
      rethrow;
    }
    Result res = Result.fromJson(response.data);
    if (res.success) {
      if(success != null) success(res);
      return res;
    }else{
      if(failure != null) failure(res);
      throw Exception(res.msg);
    }
  }

  static Future<Stream<List<int>>> pathToStream(filePath) async {
    File file = File(filePath);
    Uint8List bytes = await file.readAsBytes();
    return  MultipartFile.fromBytes(bytes).finalize();
  }
}
//
// Future<Result> request({
//   required String url,
//   bool fileUpload = false,
//   Map<String, dynamic>? data,
//   bool isToast = false
// }) async {
//   Dio dio = Dio();
//
//   await Store.reload();
//   dio.options.headers['authorization'] = await Store.auth.get() ?? "0";
//   dio.options.headers['deviceId'] = SystemPush.deviceId;
//   dio.options.headers['deviceType'] = Platform.isAndroid ? "android" : Platform.isIOS ? "ios" : "";
//   if(fileUpload) dio.options.contentType = "multipart/form-data; boundary=--${UuidV4().generate()}";
//
//   log("url:$url \n请求头：${dio.options.headers} \n请求内容：$data");
//
//   if (isToast) {
//     EasyLoading.show(maskType: EasyLoadingMaskType.black);
//   }
//   Response response;
//   try {
//     response = fileUpload ? await dio.post(config.httpHost + url, data: FormData.fromMap(data??{})) : await dio.post(config.httpHost + url, data: data);
//     Result res = Result.fromJson(response.data);
//
//     if (res.success) {
//       if (isToast) {
//         EasyLoading.dismiss();
//         EasyLoading.showSuccess(res.msg);
//       }
//       return res;
//     }else{
//       if (isToast) {
//         EasyLoading.dismiss();
//         EasyLoading.showError(res.msg);
//       }
//     }
//
//     throw Exception(res.msg);
//   } catch (e) {
//     if (isToast) {
//       EasyLoading.dismiss();
//     }
//     EasyLoading.showError("请求异常");
//     rethrow;
//   }
//
// }
